package com.jmu.edu.IMApplication.fragment;

import android.graphics.Bitmap;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.button.MaterialButton;
import com.google.android.material.imageview.ShapeableImageView;
import com.jmu.edu.IMApplication.MyApplication;
import com.jmu.edu.IMApplication.R;
import com.jmu.edu.IMApplication.event.RefreshEvent;
import com.jmu.edu.IMApplication.utils.ViewUtils;
import com.jmu.edu.IMApplication.utils.WillowUtils;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Type;

import cn.jpush.im.android.api.callback.GetAvatarBitmapCallback;
import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.android.api.model.UserInfo.Field;
import cn.jpush.im.api.BasicCallback;

import static android.text.InputType.TYPE_TEXT_FLAG_MULTI_LINE;


public class NameAndSignatureFragment extends Fragment {
    private MaterialButton backButton, confirmButton;
    private ShapeableImageView avatarImage;
    private TextView englishDescriptionText, chineseDescriptionText, hintText;
    private EditText newNameText, newSignatureText;


    public NameAndSignatureFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_name_and_signature, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private void initView() {
        avatarImage = getView().findViewById(R.id.fragment_name_and_signature_avatar);
        backButton = getView().findViewById(R.id.fragment_name_and_signature_back);
        confirmButton = getView().findViewById(R.id.fragment_name_and_signature_confirm);
        englishDescriptionText = getView().findViewById(R.id.fragment_name_and_signature_english_description);
        chineseDescriptionText = getView().findViewById(R.id.fragment_name_and_signature_chinese_description);
        hintText = getView().findViewById(R.id.fragment_name_and_signature_hint);
        newNameText = getView().findViewById(R.id.fragment_name_and_signature_new_nickname);
        newSignatureText = getView().findViewById(R.id.fragment_name_and_signature_new_signature);
        initListener();
        //填充界面的基本数据
        fillViewWithValues();
    }

    private void fillViewWithValues() {
        MyApplication.getUser().getAvatarBitmap(new GetAvatarBitmapCallback() {
            @Override
            public void gotResult(int i, String s, Bitmap bitmap) {
                if (bitmap != null) {
                    avatarImage.setImageBitmap(bitmap);
                }
            }
        });
        Bundle bundle = getArguments();
        //说明这个type是用来修改个性签名,else 则是修改昵称
        if (bundle.getString("type").equals("signature")) {
            englishDescriptionText.setText("Signature");
            chineseDescriptionText.setText("个性\n签名");
            hintText.setText("编辑你的个性签名");
            newSignatureText.setVisibility(View.VISIBLE);
            newNameText.setVisibility(View.GONE);
            newSignatureText.setText(MyApplication.getUser().getSignature());
            newNameText.setText("");
        } else {
            englishDescriptionText.setText("Nick\n    Name");
            chineseDescriptionText.setText("修改\n昵称");
            hintText.setText("你的新昵称");
            newSignatureText.setVisibility(View.GONE);
            newNameText.setVisibility(View.VISIBLE);
            newSignatureText.setText("");
            newNameText.setText(MyApplication.getUser().getNickname());
            //由于visibility会影响这两个属性，所以要重新设置
            newNameText.setLines(1);
            newNameText.setInputType(TYPE_TEXT_FLAG_MULTI_LINE);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            fillViewWithValues();
        }
    }

    private void initListener() {
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Fragment show = MyApplication.fragmentManager.findFragmentByTag("my");
                if (show == null) {
                    Toast.makeText(getContext(), "error: no fragment tag is 'my'", Toast.LENGTH_SHORT).show();
                } else {
                    ViewUtils.hideFragment(NameAndSignatureFragment.this, show, "my", R.anim.from_left, R.anim.out_right);
                }
            }
        });
        confirmButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String newSignature = newSignatureText.getText().toString().trim();
                String newName = newNameText.getText().toString().trim();
                //如果数据为空则说明不需要更新
                if (newSignature.isEmpty() && newName.isEmpty()) {
                    backButton.callOnClick();
                    return;
                }
                //如果之前的签名和现在的新签名相同,则同样不需要更新(需要当前处于修改个性签名的状态)
                if (newSignatureText.getVisibility() == View.VISIBLE && MyApplication.getUser().getSignature().equals(newSignature)) {
                    backButton.callOnClick();
                    return;
                }
                //重新显示MyFragment，且更新数据
                Fragment show = MyApplication.fragmentManager.findFragmentByTag("my");
                if (show == null) {
                    Toast.makeText(getContext(), "error: no fragment tag is 'my'", Toast.LENGTH_SHORT).show();
                } else {
                    if (newNameText.getVisibility() == View.VISIBLE) {
                        MyApplication.getUser().setNickname(newName);
                    } else {
                        MyApplication.getUser().setSignature(newSignature);
                    }
                    WillowUtils.updateMyInfo(Field.all, MyApplication.getUser(), new BasicCallback() {
                        @Override
                        public void gotResult(int i, String s) {
                            if (i != 0) {
                                Toast.makeText(getContext(), "更新信息失败，请检查网络连接", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(getContext(), "更新信息成功", Toast.LENGTH_SHORT).show();
                                EventBus.getDefault().post(new RefreshEvent("main"));
                            }
                        }
                    });
                    ViewUtils.hideFragment(NameAndSignatureFragment.this, show, "my", R.anim.from_left, R.anim.out_right);
                }
            }
        });
    }
}